import cgi
import datetime
import random
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db


def ran_word(wordLen):
    word = ''
    for i in range(wordLen):
        word += random.choice('ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz123456789')
    return word
    
class Location(db.Model):
    longitude = db.FloatProperty()
    latitude  = db.FloatProperty()
    time = db.DateTimeProperty(auto_now_add=True)
    
class Userdata(db.Model):
    username = db.StringProperty()
    passcode  = db.StringProperty()
    
class UserLog(webapp.RequestHandler):
    def post(self):
        self.redirect('/userregistration')
        
class MainUser(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user == None:
            self.redirect(users.create_login_url("/"))
            return
        
        greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" % (user.nickname(), users.create_logout_url("/")))    
        
        self.response.out.write(greeting)
        self.response.out.write('<br/>')
        user_key = db.Key.from_path('Userdata', user.nickname())
        userdata = db.get(user_key)
        
        
        
        if userdata == None :    
            userdata = Userdata(key_name = user.nickname())
            userdata.username = user.nickname()
            userdata.passcode = ran_word(7)
            userdata.put()
         
        
        self.response.out.write('<br>Encrypted Passcode: %s<br/><br>' % userdata.passcode)
        
        
        if user:
			self.redirect("/static/map.html")
	
            #print last 10 locations
            #locations = db.GqlQuery("SELECT * FROM Location ORDER BY time DESC LIMIT 10")
            #self.response.out.write('Previous locations: (Longtitude, Latitude)')
            #self.response.out.write('<ol>')
            #for location in locations:
            #
            #    self.response.out.write('<li>%.3f, %.3f at time %.8s minutes ago</li>' 
            #    %(location.latitude , location.longitude , ( datetime.datetime.now() - location.time)))
            #self.response.out.write('</ol>')
            
        else:
            
            self.redirect(users.create_login_url(self.request.uri))        
                
            
class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write("""
		<html>
			<head>
				<script type="text/JavaScript">
						function timedRefresh(timeoutPeriod) {
							setTimeout("location.reload(true);",timeoutPeriod);
						}
				</script>
			</head>
		<body onload="JavaScript:timedRefresh(3000);">""")

        locations = db.GqlQuery("SELECT * FROM Location ORDER BY time DESC LIMIT 100")
        
        # Write the submission form and the footer of the page
        self.response.out.write("""
              <form action="/sign" method="post">
                Latitude<div><textarea name="latitude" rows="1" cols="30"></textarea></div>Longitude
				<div><textarea name="longitude" rows="1" cols="30"></textarea></div>
                <div><input type="submit" value="Submit"></div>
								
              </form>
            </body>
          </html>""")

class MapDisplay(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        user_key = db.Key.from_path('Userdata', user.nickname())
        userdata = db.get(user_key)
        locations = db.GqlQuery("SELECT * FROM Location ORDER BY time DESC LIMIT 100")
        self.response.headers['Content-Type'] = 'application/json'
        
        jsondata = '{\"passcode\":\"%s\"' % userdata.passcode
        jsondata += ', \"locations\":['
        counter = 0
        for location in locations:
            timedif = datetime.datetime.now() - location.time
            if counter == 0:
                jsondata += '{\"lat\":%.3f,\"lng\":%.3f,\"time\":\"%.8s\"}' %(location.latitude , location.longitude , timedif)
            else:
                jsondata += ', {\"lat\":%.3f,\"lng\":%.3f,\"time\":\"%.8s\"}' %(location.latitude , location.longitude , timedif)
            counter += 1
        jsondata+= ']}'
        self.response.out.write(jsondata)



class Location_directory(webapp.RequestHandler):
    def post(self):
        location = Location()	
        location.longitude =  float(self.request.get('longitude'))
        location.latitude  =  float(self.request.get('latitude'))
        location.put()
        self.response.out.write('hi')
        self.redirect('/')

class Logout(webapp.RequestHandler):
    def get(self):
        self.redirect(users.create_logout_url("/"))

                
		
application = webapp.WSGIApplication(
                                     [('/adsf',           MainPage),
                                      ('/sign',       Location_directory),
				      ('/locations',  MapDisplay),
                                      ('/',      MainUser),
                                      ('/reglog',            UserLog),
                                      ('/logout',     Logout)],
                                     debug=True)
									 
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
  main()
